package com.uphone.magicleafteacher.pro.activity;

import android.arch.lifecycle.LifecycleOwner;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.radish.baselibrary.Intent.IntentData;
import com.radish.baselibrary.Intent.IntentUtils;
import com.radish.framelibrary.view.glide.GlideUtils;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.uphone.magicleafteacher.MyApp;
import com.uphone.magicleafteacher.R;
import com.uphone.magicleafteacher.base.BaseGActivity;
import com.uphone.magicleafteacher.http.ApiService;
import com.uphone.magicleafteacher.http.FailureConsumer;
import com.uphone.magicleafteacher.http.RxSchedulers;
import com.uphone.magicleafteacher.http.SuccessfulConsumer;
import com.uphone.magicleafteacher.util.AudioPlayProgressUtil;
import com.uphone.magicleafteacher.util.CommonUtil;
import com.uphone.magicleafteacher.util.DateUtils;
import com.uphone.magicleafteacher.util.GsonUtils;
import com.uphone.magicleafteacher.vo.RetellCorrectBean;
import com.uphone.magicleafteacher.vo.WorkcorrectionEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

public class RetellCorrectActivity extends BaseGActivity {

    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.tv_bookname)
    TextView tvBookname;
    @BindView(R.id.tv_ask)
    TextView tvAsk;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rela)
    RelativeLayout rela;
    @BindView(R.id.text_yu)
    TextView textYu;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.sb_audio)
    SeekBar sbAudio;
    @BindView(R.id.tv_duration)
    TextView tvDuration;
    @BindView(R.id.ll_play)
    LinearLayout llPlay;
    @BindView(R.id.img_preview)
    ImageView imgPreview;
    @BindView(R.id.reative)
    RelativeLayout reative;
    @BindView(R.id.text_integral)
    TextView textIntegral;
    @BindView(R.id.linea)
    LinearLayout linea;
    @BindView(R.id.img_jobresult)
    ImageView imgJobresult;
    @BindView(R.id.rl_teacher)
    RelativeLayout rlTeacher;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.ll_btn)
    LinearLayout llBtn;
    private AudioPlayProgressUtil audioPlayUtils;
    @IntentData
    private int status;
    @IntentData
    private int id;
    private String workPic;
    private String remarkPic;
    private String audioPath;

    @Override
    protected void initLayoutBefore() {
        super.initLayoutBefore();
        isEventBus = true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefresh(WorkcorrectionEvent outGroupEvent) {
        //刷新
        initData();
    }

    @Override
    protected void initBundle() {

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_retell_correct;
    }

    @Override
    protected void initView() {
        audioPlayUtils = new AudioPlayProgressUtil();
        if (status == 2) {
            llBtn.setVisibility(View.GONE);
            rlTeacher.setVisibility(View.VISIBLE);
        } else {
            llBtn.setVisibility(View.VISIBLE);
            rlTeacher.setVisibility(View.GONE);
        }

    }

    @Override
    protected void initTitle() {
        initTitle("复述");
    }

    @Override
    protected void initData() {
        MyApp.apiService(ApiService.class)
                .repeatWorkDetail("" + id)
                .compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    showLoading();
                })
                .doFinally(() -> {
                    closeLoading();
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        RetellCorrectBean bean = GsonUtils.getGson().fromJson(jsonObject, RetellCorrectBean.class);
                        if (bean != null && bean.getRepeatWorkDetail() != null) {
                            loadData(bean.getRepeatWorkDetail());
                        }
                    }
                }, new FailureConsumer());
    }

    private void loadData(RetellCorrectBean.RepeatWorkDetailBean bean) {
        if (bean.getIsRemark() == 2) {
            llBtn.setVisibility(View.GONE);
            rlTeacher.setVisibility(View.VISIBLE);
        } else {
            llBtn.setVisibility(View.VISIBLE);
            rlTeacher.setVisibility(View.GONE);
        }
        GlideUtils.getInstance().loadCornerImage(this, CommonUtil.getImageUrl(bean.getBookPic()), SizeUtils.dp2px(5), ivPic);
        tvBookname.setText(CommonUtil.getStr(bean.getBookName()));
        tvAsk.setText("学生：" + CommonUtil.getStr(bean.getStudentName()));
        tvTime.setText("提交时间：" + CommonUtil.getStr(bean.getAnswerTime()));
        textIntegral.setText(CommonUtil.getStr(bean.getJifen() + ""));
        audioPath = bean.getAudioPath();
        workPic = bean.getRepeatPic();
        GlideUtils.getInstance().loadCornerImage(this, CommonUtil.getImageUrl(workPic), SizeUtils.dp2px(8), imgPreview);
        remarkPic = bean.getRemarkPic();
        GlideUtils.getInstance().loadCornerImage(this, CommonUtil.getImageUrl(remarkPic), SizeUtils.dp2px(8), imgJobresult);
    }

    @Override
    protected void initListener() {
        audioPlayUtils.setProgressListener(new AudioPlayProgressUtil.ProgressListener() {
            @Override
            public void start() {
                ivPlay.setSelected(true);
            }

            @Override
            public void progress(int progress, int currentDuration, int totalDuration) {
                if (progress != sbAudio.getProgress())
                    sbAudio.setProgress(progress);
                tvDuration.setText("" + DateUtils.getTimeFormLong(currentDuration));
            }

            @Override
            public void completion() {
                ivPlay.setSelected(false);
                tvDuration.setText("00:00:00");
            }

            @Override
            public void stop() {
                ivPlay.setSelected(false);

            }
        });
    }

    @OnClick({R.id.iv_play, R.id.img_preview, R.id.img_jobresult, R.id.btn_submit, R.id.btn_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_play:
                if (view.isSelected()) {
                    audioPlayUtils.stop();
                } else {
                    audioPlayUtils.play(CommonUtil.getVideoUrl(audioPath));
                }
                break;
            case R.id.img_preview:
                CommonUtil.openBigPic(CommonUtil.getImageUrl(workPic));
                break;
            case R.id.img_jobresult:
                CommonUtil.openBigPic(CommonUtil.getImageUrl(remarkPic));
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(workPic)) {
                    ToastUtils.showShort("暂无作业可批改");
                    return;
                }
                IntentUtils.getInstance()
                        .with(this, WorkcorrectioningActivity.class)
                        .putInt("id", id)
                        .putInt("type", 2)
                        .putString("filePath", CommonUtil.getImageUrl(workPic))
                        .putString("saveFilePath", getFilesDir() + "temp.png")
                        .start();
                break;
            case R.id.btn_cancel:
                //驳回
                rejectRepeatWork(id);
                break;
        }
    }

    public void rejectRepeatWork(int liveId) {
        MyApp.apiService(ApiService.class)
                .rejectRepeatWork(liveId + "")
                .compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    showLoading();
                })
                .doFinally(() -> {
                    closeLoading();
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        EventBus.getDefault().post(new WorkcorrectionEvent());
                        CommonUtil.quitActivity(RetellCorrectActivity.this,"已驳回");
                    }
                }, new FailureConsumer());

    }

}
